package com.kyrioscraft.cloud.thead.jdklab.tools.reentrant;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @Author kyrioscraft
 * @Date 2019/2/18 10:04
 * @Description 同时允许多个线程访问acquire和release之间的资源
 **/
public class SemaphoreDemo implements Runnable{
    final Semaphore semaphore = new Semaphore(5);
    @Override
    public void run() {
        try {
            semaphore.acquire();
            Thread.sleep(2000);
            System.out.println(Thread.currentThread().getId()+" done");
            semaphore.release();
        } catch (InterruptedException e) {

        }
    }

    public static void main(String[] args) {
        ExecutorService exec= Executors.newFixedThreadPool(20);
        final SemaphoreDemo demo = new SemaphoreDemo();
        for(int i=0; i<20 ;i++ ) {
            exec.submit(demo);
        }
    }
}
